/**
 * 数据插入组件 - 支持静态和动态数据插入
 */
import React, { useState, useEffect } from 'react';
import { 
  Modal, 
  Steps, 
  Select, 
  Table, 
  Button, 
  Space, 
  message, 
  Radio, 
  Form, 
  Input,
  Tag,
  Alert,
  Checkbox
} from 'antd';
import { DatabaseOutlined, TableOutlined, FieldStringOutlined } from '@ant-design/icons';
import { request } from '@umijs/max';

interface DataSourceItem {
  id: number;
  name: string;
  type: string;
}

interface TableItem {
  name: string;
  comment?: string;
}

interface FieldItem {
  name: string;
  type: string;
  comment?: string;
}

interface DataRow {
  [key: string]: any;
}

interface FilterCondition {
  field: string;
  operator: string;
  value: string;
}

interface DataInsertionProps {
  visible: boolean;
  onCancel: () => void;
  onConfirm: (insertionData: any) => void;
  dataSources: DataSourceItem[];
}

const DataInsertion: React.FC<DataInsertionProps> = ({
  visible,
  onCancel,
  onConfirm,
  dataSources,
}) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [insertionType, setInsertionType] = useState<'static' | 'dynamic'>('static');
  const [selectedDataSource, setSelectedDataSource] = useState<DataSourceItem | null>(null);
  const [tables, setTables] = useState<TableItem[]>([]);
  const [selectedTable, setSelectedTable] = useState<string>('');
  const [fields, setFields] = useState<FieldItem[]>([]);
  const [selectedFields, setSelectedFields] = useState<string[]>([]);
  const [tableData, setTableData] = useState<DataRow[]>([]);
  const [selectedRows, setSelectedRows] = useState<DataRow[]>([]);
  const [filterConditions, setFilterConditions] = useState<FilterCondition[]>([]);
  const [loading, setLoading] = useState(false);

  // 重置状态
  const resetState = () => {
    setCurrentStep(0);
    setInsertionType('static');
    setSelectedDataSource(null);
    setTables([]);
    setSelectedTable('');
    setFields([]);
    setSelectedFields([]);
    setTableData([]);
    setSelectedRows([]);
    setFilterConditions([]);
  };

  // 获取表列表
  const fetchTables = async (dataSourceId: number) => {
    setLoading(true);
    try {
      const response = await request(`/api/data-sources/${dataSourceId}/tables`);
      setTables(response.tables || []);
    } catch (error: any) {
      message.error('获取表列表失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 获取字段列表
  const fetchFields = async (dataSourceId: number, tableName: string) => {
    setLoading(true);
    try {
      const response = await request(`/api/data-sources/${dataSourceId}/tables/${tableName}/fields`, {
        params: { identify_types: true }
      });
      setFields(response || []);
    } catch (error: any) {
      message.error('获取字段列表失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 获取表数据（仅静态模式）
  const fetchTableData = async (dataSourceId: number, tableName: string, fields: string[]) => {
    if (insertionType !== 'static') return;
    
    setLoading(true);
    try {
      const response = await request(`/api/data-sources/${dataSourceId}/tables/${tableName}/data`, {
        params: { 
          fields: fields.join(','),
          limit: 100 
        }
      });
      setTableData(response.data || []);
    } catch (error: any) {
      message.error('获取表数据失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 步骤配置
  const steps = [
    {
      title: '选择类型',
      description: '选择数据插入类型',
    },
    {
      title: '选择数据源',
      description: '选择要使用的数据源',
    },
    {
      title: '选择表',
      description: '选择要查询的表',
    },
    {
      title: '选择字段',
      description: '选择要插入的字段',
    },
    {
      title: insertionType === 'static' ? '选择数据' : '设置条件',
      description: insertionType === 'static' ? '选择具体的数据行' : '设置筛选条件',
    },
  ];

  // 下一步
  const nextStep = () => {
    if (currentStep < steps.length - 1) {
      setCurrentStep(currentStep + 1);
    }
  };

  // 上一步
  const prevStep = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  };

  // 处理数据源选择
  const handleDataSourceChange = (dataSourceId: number) => {
    const dataSource = dataSources.find(ds => ds.id === dataSourceId);
    setSelectedDataSource(dataSource || null);
    if (dataSource) {
      fetchTables(dataSourceId);
    }
  };

  // 处理表选择
  const handleTableChange = (tableName: string) => {
    setSelectedTable(tableName);
    if (selectedDataSource) {
      fetchFields(selectedDataSource.id, tableName);
    }
  };

  // 处理字段选择
  const handleFieldsChange = (fieldNames: string[]) => {
    setSelectedFields(fieldNames);
    if (insertionType === 'static' && selectedDataSource && selectedTable && fieldNames.length > 0) {
      fetchTableData(selectedDataSource.id, selectedTable, fieldNames);
    }
  };

  // 确认插入
  const handleConfirm = () => {
    if (insertionType === 'static') {
      if (selectedRows.length === 0) {
        message.warning('请选择要插入的数据行');
        return;
      }
      onConfirm({
        type: 'static',
        dataSource: selectedDataSource,
        table: selectedTable,
        fields: selectedFields,
        data: selectedRows,
      });
    } else {
      onConfirm({
        type: 'dynamic',
        dataSource: selectedDataSource,
        table: selectedTable,
        fields: selectedFields,
        conditions: filterConditions,
      });
    }
    resetState();
  };

  // 渲染步骤内容
  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Radio.Group 
              value={insertionType} 
              onChange={(e) => setInsertionType(e.target.value)}
              size="large"
            >
              <Space direction="vertical" size="large">
                <Radio.Button value="static" style={{ height: '60px', padding: '20px' }}>
                  <div>
                    <div style={{ fontSize: '16px', fontWeight: 'bold' }}>📌 静态数据插入</div>
                    <div style={{ fontSize: '12px', color: '#666' }}>选择具体的数据行，数据固定不变</div>
                  </div>
                </Radio.Button>
                <Radio.Button value="dynamic" style={{ height: '60px', padding: '20px' }}>
                  <div>
                    <div style={{ fontSize: '16px', fontWeight: 'bold' }}>🔄 动态数据插入</div>
                    <div style={{ fontSize: '12px', color: '#666' }}>设置筛选条件，实时获取最新数据</div>
                  </div>
                </Radio.Button>
              </Space>
            </Radio.Group>
          </div>
        );

      case 1:
        return (
          <div>
            <Alert
              message={`已选择：${insertionType === 'static' ? '静态数据插入' : '动态数据插入'}`}
              type="info"
              style={{ marginBottom: 16 }}
            />
            <Form.Item label="选择数据源">
              <Select
                placeholder="请选择数据源"
                value={selectedDataSource?.id}
                onChange={handleDataSourceChange}
                loading={loading}
              >
                {dataSources.map(ds => (
                  <Select.Option key={ds.id} value={ds.id}>
                    <Space>
                      <DatabaseOutlined />
                      {ds.name} ({ds.type})
                    </Space>
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </div>
        );

      case 2:
        return (
          <Form.Item label="选择表">
            <Select
              placeholder="请选择表"
              value={selectedTable}
              onChange={handleTableChange}
              loading={loading}
            >
              {tables.map(table => (
                <Select.Option key={table.name} value={table.name}>
                  <Space>
                    <TableOutlined />
                    {table.name}
                    {table.comment && <span style={{ color: '#999' }}>({table.comment})</span>}
                  </Space>
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        );

      case 3:
        return (
          <Form.Item label="选择字段">
            <Checkbox.Group
              value={selectedFields}
              onChange={handleFieldsChange}
              style={{ width: '100%' }}
            >
              <Space direction="vertical" style={{ width: '100%' }}>
                {fields.map(field => (
                  <Checkbox key={field.name} value={field.name}>
                    <Space>
                      <FieldStringOutlined />
                      {field.name}
                      <Tag size="small">{field.type}</Tag>
                      {field.comment && <span style={{ color: '#999' }}>({field.comment})</span>}
                    </Space>
                  </Checkbox>
                ))}
              </Space>
            </Checkbox.Group>
          </Form.Item>
        );

      case 4:
        if (insertionType === 'static') {
          const columns = selectedFields.map(field => ({
            title: field,
            dataIndex: field,
            key: field,
          }));

          return (
            <div>
              <Alert
                message={`请选择要插入的数据行（已选择 ${selectedRows.length} 行）`}
                type="info"
                style={{ marginBottom: 16 }}
              />
              <Table
                columns={columns}
                dataSource={tableData}
                rowSelection={{
                  selectedRowKeys: selectedRows.map((_, index) => index),
                  onChange: (selectedRowKeys, selectedRowsData) => {
                    setSelectedRows(selectedRowsData);
                  },
                }}
                pagination={{ pageSize: 10 }}
                size="small"
                loading={loading}
              />
            </div>
          );
        } else {
          return (
            <div>
              <Alert
                message="设置筛选条件，发送时将根据条件获取最新数据"
                type="info"
                style={{ marginBottom: 16 }}
              />
              <div>
                <Button 
                  type="dashed" 
                  onClick={() => setFilterConditions([...filterConditions, { field: '', operator: '=', value: '' }])}
                  style={{ marginBottom: 16 }}
                >
                  添加筛选条件
                </Button>
                {filterConditions.map((condition, index) => (
                  <div key={index} style={{ marginBottom: 8 }}>
                    <Space>
                      <Select
                        placeholder="选择字段"
                        value={condition.field}
                        onChange={(value) => {
                          const newConditions = [...filterConditions];
                          newConditions[index].field = value;
                          setFilterConditions(newConditions);
                        }}
                        style={{ width: 120 }}
                      >
                        {selectedFields.map(field => (
                          <Select.Option key={field} value={field}>{field}</Select.Option>
                        ))}
                      </Select>
                      <Select
                        value={condition.operator}
                        onChange={(value) => {
                          const newConditions = [...filterConditions];
                          newConditions[index].operator = value;
                          setFilterConditions(newConditions);
                        }}
                        style={{ width: 80 }}
                      >
                        <Select.Option value="=">=</Select.Option>
                        <Select.Option value="!=">!=</Select.Option>
                        <Select.Option value=">">></Select.Option>
                        <Select.Option value="<"><</Select.Option>
                        <Select.Option value="LIKE">包含</Select.Option>
                      </Select>
                      <Input
                        placeholder="值"
                        value={condition.value}
                        onChange={(e) => {
                          const newConditions = [...filterConditions];
                          newConditions[index].value = e.target.value;
                          setFilterConditions(newConditions);
                        }}
                        style={{ width: 120 }}
                      />
                      <Button
                        type="text"
                        danger
                        onClick={() => {
                          const newConditions = filterConditions.filter((_, i) => i !== index);
                          setFilterConditions(newConditions);
                        }}
                      >
                        删除
                      </Button>
                    </Space>
                  </div>
                ))}
              </div>
            </div>
          );
        }

      default:
        return null;
    }
  };

  return (
    <Modal
      title="数据插入"
      open={visible}
      onCancel={() => {
        resetState();
        onCancel();
      }}
      width={800}
      footer={
        <Space>
          <Button onClick={() => { resetState(); onCancel(); }}>
            取消
          </Button>
          {currentStep > 0 && (
            <Button onClick={prevStep}>
              上一步
            </Button>
          )}
          {currentStep < steps.length - 1 ? (
            <Button 
              type="primary" 
              onClick={nextStep}
              disabled={
                (currentStep === 1 && !selectedDataSource) ||
                (currentStep === 2 && !selectedTable) ||
                (currentStep === 3 && selectedFields.length === 0)
              }
            >
              下一步
            </Button>
          ) : (
            <Button 
              type="primary" 
              onClick={handleConfirm}
              disabled={
                insertionType === 'static' ? selectedRows.length === 0 : false
              }
            >
              确认插入
            </Button>
          )}
        </Space>
      }
    >
      <Steps current={currentStep} items={steps} style={{ marginBottom: 24 }} />
      {renderStepContent()}
    </Modal>
  );
};

export default DataInsertion;
